package com.zhiyun.hxzy.controller.admin;

import com.zhiyun.hxzy.domain.Programmer;
import com.zhiyun.hxzy.service.ProgrammerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/admin/programmer")
public class ProgrammerController {
    @Autowired
    private ProgrammerService programmerService;

    @RequestMapping("/add")
    public String addProgrammer(Programmer programmer, HttpServletRequest request){
        programmerService.addProgrammer (programmer);
        return "redirect:" + request.getContextPath() + "/admin/programmer/all";
    }

    @RequestMapping("/updateStatus")
    public String updateStatus(Long[] ids,Integer status, HttpServletRequest request){
        programmerService.updateStatus(ids,status);
        return "redirect:" + request.getContextPath() + "/admin/programmer/all";
    }

    @RequestMapping("/all")
    public ModelAndView all(@RequestParam(defaultValue = "0") int pageNum, @RequestParam(defaultValue = "5") int pageSize){
        ModelAndView modelAndView=new ModelAndView ();
        ModelMap modelMap = modelAndView.getModelMap ();
        Page<Programmer> programmers = programmerService.findAll (pageNum-1, pageSize);
        modelMap.addAttribute ("programmers",programmers);
        modelAndView.setViewName ("./admin/programmers_list");
        return modelAndView;
    }
    @RequestMapping("/findById")
    public String findByIdProgrammer(Long id,ModelMap map){
        Programmer programmer = programmerService.findByIdProgrammer(id);
        map.addAttribute("programmer",programmer);
        return "admin/programmer_update";

    }
    @RequestMapping("/update")
    public String updateProgrammer(Programmer programmer, HttpServletRequest request){
        programmerService.updateProgrammer(programmer);
        return "redirect:" + request.getContextPath() + "/admin/programmer/all";
    }
    @RequestMapping("/del")
    public String delete(Long id, HttpServletRequest request){
        String referer = request.getHeader("referer");
        programmerService.del(id);
        return "redirect:" + referer;
    }
}
